package com.yx.front.manager;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yx.front.config.global.BizException;
import com.yx.front.config.global.CommonResult;
import com.yx.front.converter.SysUserConverter;
import com.yx.front.enums.IntBoolean;
import com.yx.front.enums.TimeFormat;
import com.yx.front.model.AuditRelation;
import com.yx.front.model.FriendRelation;
import com.yx.front.model.MessageRecord;
import com.yx.front.model.SysUser;
import com.yx.front.model.param.AuditRelationParam;
import com.yx.front.model.vo.FriendApplyVo;
import com.yx.front.model.vo.SysUserVo;
import com.yx.front.service.AuditRelationService;
import com.yx.front.service.FriendRelationService;
import com.yx.front.service.MessageRecordService;
import com.yx.front.service.SysUserService;
import com.yx.front.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author yangx
 */
@Slf4j
@Component
public class AuditRelationManager {
    @Resource
    private FriendRelationService friendRelationService;
    @Resource
    private AuditRelationService auditRelationService;
    @Resource
    private SysUserConverter sysUserConverter;
    @Resource
    private MessageRecordService messageRecordService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private LoginUtil loginUtil;


    public CommonResult<List<FriendApplyVo>> getApplyList() {
        SysUser currentUser = loginUtil.getCurrentUser();
        LambdaQueryWrapper<AuditRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuditRelation::getAuditBy, currentUser.getId());
        wrapper.orderByDesc(AuditRelation::getCreateTime);
        List<AuditRelation> list = auditRelationService.list(wrapper);
        List<FriendApplyVo> result = handlerResult(list);
        return CommonResult.success(result);
    }

    private List<FriendApplyVo> handlerResult(List<AuditRelation> list) {
        List<FriendApplyVo> vos = new ArrayList<>();
        list.forEach(one -> {
            FriendApplyVo vo = new FriendApplyVo();
            vo.setContext(one.getContext());
            String format = DateUtil.format(one.getCreateTime(), TimeFormat.TIME_FORMAT);
            vo.setCreateTime(format);
            vo.setId(one.getId());
            vo.setStatus(one.getStatus().equals(IntBoolean.YES.getKey()));
            vo.setType(one.getAuditStatus().equals(IntBoolean.YES.getKey()));
            SysUserVo sysUserVo = getSysUserVo(one.getApplyId());
            vo.setApplyUser(sysUserVo);
            vos.add(vo);
        });
        return vos;
    }

    public String audit(AuditRelationParam param){
        AuditRelation auditRelation = auditRelationService.getById(param.getId());
        if (Objects.isNull(auditRelation)){
            throw new BizException("非法操作，记录不存在");
        }
        if (IntBoolean.YES.getKey().equals(param.getKeyword())) {
            SysUser currentUser = loginUtil.getCurrentUser();
            FriendRelation relation = new FriendRelation();
            relation.setUserId(currentUser.getId());
            relation.setFriendId(auditRelation.getApplyId());
            relation.setCreateTime(DateUtil.date());
            relation.setModifyTime(DateUtil.date());
            relation.setOperatorId(currentUser.getId());
            relation.setOperatorName(currentUser.getUserName());
            boolean save = friendRelationService.save(relation);
            //更改审核记录
            LambdaUpdateWrapper<AuditRelation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(AuditRelation::getId, param.getId())
                    .set(AuditRelation::getStatus, IntBoolean.YES.getKey())
                    .set(AuditRelation::getAuditStatus, IntBoolean.YES.getKey());
            boolean update = auditRelationService.update(wrapper);
            //增加一条默认聊天记录
            MessageRecord record = new MessageRecord();
            record.setContext("你们已经是好友啦，快来聊天吧");
            record.setSendTime(DateUtil.date());
            record.setFromId(currentUser.getId());
            record.setToId(auditRelation.getApplyId());
            boolean ok = messageRecordService.save(record);
            if(update && save && ok){
                return "成功添加对方为好友";
            }
            return "添加好友失败";
        }
        //更改审核记录
        LambdaUpdateWrapper<AuditRelation> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AuditRelation::getId, param.getId())
                .set(AuditRelation::getStatus, IntBoolean.YES.getKey())
                .set(AuditRelation::getAuditStatus, IntBoolean.NO.getKey());
        boolean update = auditRelationService.update(wrapper);
        if (update){
            return "拒绝添加好友成功";
        }
        return "拒绝添加好友失败";
    }

    public CommonResult<List<FriendApplyVo>> getMyApply() {
        SysUser currentUser = loginUtil.getCurrentUser();
        LambdaQueryWrapper<AuditRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuditRelation::getApplyId, currentUser.getId());
        wrapper.eq(AuditRelation::getStatus, IntBoolean.NO.getKey());
        List<AuditRelation> list = auditRelationService.list(wrapper);
        //处理结果返回
        return fillData(list);
    }

    private CommonResult<List<FriendApplyVo>> fillData(List<AuditRelation> list) {
        List<FriendApplyVo> result = new ArrayList<>();
        list.forEach(one->{
            FriendApplyVo vo = new FriendApplyVo();
            vo.setType(one.getAuditStatus().equals(IntBoolean.YES.getKey()));
            vo.setContext(one.getContext());
            vo.setId(one.getId());
            vo.setStatus(one.getStatus().equals(IntBoolean.YES.getKey()));
            vo.setCreateTime(DateUtil.format(one.getCreateTime(), TimeFormat.TIME_FORMAT));
            SysUserVo sysUserVo = getSysUserVo(one.getAuditBy());
            vo.setApplyUser(sysUserVo);
            result.add(vo);
        });
        return CommonResult.success(result);
    }

    private SysUserVo getSysUserVo(Long id) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getId, id);
        SysUser user = sysUserService.getOne(wrapper);
        return sysUserConverter.sysUserToVo(user);
    }
}
